
package org.vasil.jouikov.testmongodb

import com.gmongo.GMongoClient
import com.mongodb.ServerAddress
import com.mongodb.WriteConcern

def name='vasil'

println "Hello $name!"

    def addrs = [
        new ServerAddress('192.168.200.101', 10001), // node01
        new ServerAddress('192.168.200.102', 10001), // node02
        new ServerAddress('192.168.200.103', 10001)  // node03
    ]

    // Default mongo connection
    final def db = new GMongoClient(addrs).getDB('test')
 
    while(true) {

        println "Write:"
        try {
            // Default mongo connection
            db.coll.insert(['test': 'name'], WriteConcern.NORMAL) // Does not verify write by default! Fire-and-forget

            println "May have wrote to primary! WriteConcern.NORMAL"

            Thread.sleep(3000)
        }
        catch(error) {
            println "\t\tCould not communicate with replica set!\n$error"
        }


        try {
            // Mongo connection which validates writes have occurred
            db.coll.insert(['test': 'name'], WriteConcern.SAFE) // Verifies write!

            println "Wrote to primary! WriteConcern.SAFE"

            Thread.sleep(3000)
        }
        catch(error) {
            println "\t\tCould not write to primary!\n$error"
        }

        try {
            // Write to primary and at least one secondary
            db.coll.insert(['test': 'name'], WriteConcern.REPLICAS_SAFE)

            println "Wrote to primary and replicated to one other! WriteConcern.REPLICAS_SAFE"

            Thread.sleep(3000)
        }
        catch(error) {
            println "\t\tCould not write to primary and replicate to one other!\n$error"
        }


        println "Read:"
        try {
            // Reads from primary, so will error when primary down
            def cursor = db.coll.find([:])
            println "cursor=$cursor"
            cursor.each {
            }
            cursor.close()

            println "Read from primary!WriteConcern.NORMAL"

            Thread.sleep(3000)
        }
        catch(error) {
            println "\t\tCould not read from primary!\n$error"
        }

        try { // need set slaveOk()
            // Read from primary or secondary
            def cursor = db.coll.find([:])
            println "cursor=$cursor"
            cursor.each {
            }
            cursor.close()

            println "Read from secondary or primary! slaveOk WriteConcern.NORMAL"

            Thread.sleep(3000)
        }
        catch(error) {
            println "\t\tCould not read from anywhere!\n$error"
        }


    }
